package com.neu.flashmall.product.service.impl;

import com.neu.common.constant.RedisRegion;
import com.neu.flashmall.product.entity.PmsAttr;
import com.neu.flashmall.product.entity.PmsAttrGroup;
import com.neu.flashmall.product.mapper.PmsAttrGroupMapper;
import com.neu.flashmall.product.service.PmsAttrGroupService;
import com.neu.flashmall.product.service.PmsAttrService;
import lombok.Setter;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PmsAttrGroupServiceImpl implements PmsAttrGroupService {

    @Resource
    private PmsAttrGroupMapper pmsAttrGroupMapper;

    @Resource
    private PmsAttrService pmsAttrService;

    @Override
    public String add(PmsAttrGroup pmsAttrGroup) {
        if(checkDuplicate(-1L, pmsAttrGroup.getAttrGroupName(), pmsAttrGroup.getCategoryId()) == 1){
            return "该类别下已经存在同名属性组";
        }
        if(pmsAttrGroup.getCategoryId() <= 0){
            return "属性组所属类别异常";
        }
        int result = this.pmsAttrGroupMapper.insertSelective(pmsAttrGroup);
        if(result == 1) return "添加成功";
        return "数据库异常";
    }

    @Override
    public String update(PmsAttrGroup pmsAttrGroup) {
        if(checkDuplicate(pmsAttrGroup.getId(), pmsAttrGroup.getAttrGroupName(), pmsAttrGroup.getCategoryId()) == 1){
            return "该类别下已经存在同名属性组";
        }
        if(pmsAttrGroup.getCategoryId() <= 0){
            return "属性组所属类别异常";
        }
        int result = this.pmsAttrGroupMapper.updateByPrimaryKeySelective(pmsAttrGroup);
        if(result == 1) return "更新成功";
        return "数据库异常";
    }

    @Override
     public List<PmsAttrGroup> getAllAttrGroup() {
        return this.pmsAttrGroupMapper.selectAll();
    }

    @Override
    @Transactional
    public String delete(Long id) {
        if(pmsAttrService.canDeleteAttrGroup(id) >0 ){
            return "该属性组下的存在属性被SPU引用，无法删除";
        }
        int result = this.pmsAttrGroupMapper.deleteByPrimaryKey(id);
        pmsAttrService.deleteAllByGroup(Integer.valueOf(String.valueOf(id)));
        if(result == 1) return "删除成功";
        return "数据库异常";
    }

    public PmsAttrGroup getOneById(Long id){
        return this.pmsAttrGroupMapper.selectByPrimaryKey(id);
    }

    private int checkDuplicate(Long id,String name,Long categoryId){
        if(id == null) id = -1L;
        List<PmsAttrGroup> duplicate = this.pmsAttrGroupMapper.selectDuplicate(id, name, categoryId);
        if(duplicate.isEmpty()) return 0;
        return 1;
    }
}
